<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogFlag"
      class="avue-dialog avue-dialog--top"
      width="60%"
      @close="cancel"
    >
      <div class="center-container">
        <el-steps style="width: 80%; max-width: 800px" :active="active" align-center>
          <el-step title="第一步"/>
          <el-step title="第二步"/>
          <el-step title="第三步"/>
        </el-steps>
      </div>
      <div style="margin: 10px 70px;">
        <el-form :rules="rules" ref="ruleForm" :model="dataForm" label-width="100px" @submit.native.prevent class="product-form">
          <div v-if="active === 0">
            <el-form-item label="动作名称:" prop="actionName">
              <el-input v-model="dataForm.actionName" :disabled="type == 'view'" size="small" placeholder="请输入动作名称"></el-input>
            </el-form-item>
            <el-form-item label="动作类型:" prop="actionType">
              <el-select v-model="dataForm.actionType" :disabled="type == 'view'" size="small" style="width: 100%" placeholder="请选择动作类型">
                <el-option
                  v-for="item in actionDict"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div v-if="active == 1">
            <!--     发送消息       -->
            <div v-if="dataForm.actionType === '1'">
              <div>
                <el-row>
                  <el-form-item label="选择通道:" prop="message.msgChannel">
                    <el-select  @change="selectChannel" :disabled="type == 'view'" v-model="dataForm.message.msgChannel" size="small" style="width: 100%" placeholder="请选择消息通道">
                      <el-option
                        v-for="item in channelList"
                        :key="item.appId"
                        :label="item.appName"
                        :value="item.appId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="选择模板:" prop="message.msgTemplate">
                    <el-select  :disabled="templateDisabled || type == 'view'" @change="selectTemplate" v-model="dataForm.message.msgTemplate" size="small" style="width: 100%" placeholder="请选择消息模板">
                      <el-option
                        v-for="item in templateList"
                        :key="item.templateId"
                        :label="item.templateName"
                        :value="item.templateId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
              </div>
            </div>
          </div>

          <div v-if="active == 2">
            <!-- 发送消息-->
            <!--设置消息参数-->
            <el-form-item label-width="120px" v-for="item in configData" :label="item.label+':'" :prop="item.prop">
              <el-row v-if="item.type=='input'">
                <el-col>
                  <el-input  v-model="dataForm.message[item.prop]" :disabled="(type == 'view')||item.disabled" size="small" style="width: 100%" :placeholder="item.placeholder">
                  </el-input>
                </el-col>
              </el-row>

              <el-row v-if="item.type=='select'">
                <el-col>
                  <el-select @change="usersChange"  multiple  v-model="dataForm.message[item.prop]" :disabled="type == 'view'||item.disabled" size="small" style="width: 100%" :placeholder="item.placeholder">
                    <el-option v-for="item in users" :key="parseInt(item.id)" :label="item.nickname" :value="parseInt(item.id)" />
                  </el-select>
                </el-col>
              </el-row>

              <el-row v-if="item.type=='tag'">

                  <el-tag
                          :key="tag"
                          v-for="tag in dataForm.message[item.prop]"
                          :closable="!(type=='view')"
                          :disable-transitions="false"
                          @close="handleClose(tag,item.prop)">
                    {{tag}}
                  </el-tag>

                  <el-input
                    class="input-new-tag"
                    v-show="item.isShow"
                    v-model="tagValueList[item.prop]"
                    :ref="item.prop"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(item.prop)"
                    @blur="handleInputConfirm(item.prop)"
                  >
                  </el-input>
                  <el-button v-if="!item.isShow" :disabled="type == 'view'" class="button-new-tag" size="small" @click="showInput(item.prop)">新增</el-button>

              </el-row>
              <el-row v-if="item.type=='editor'">
                <vue-editor
                  ref="editor"

                  :disabled="true"
                  v-model="dataForm.message[item.prop]"
                  style="width: 99%;"
                ></vue-editor>
              </el-row>

            </el-form-item>
          </div>
        </el-form>
      </div>

      <div class="dialog-footer">
        <el-button style="margin-top: 12px" v-if="active != 0" @click="previous">上一步</el-button>
        <el-button style="margin-top: 12px" v-if="(active !== 2) && !(dataForm.actionType === '3' && active === 1)" @click="next">下一步</el-button>
        <el-button style="margin-top: 12px" v-if="((dataForm.outputWay === 'MQTT') && (active === 1)) && (type != 'view') " type="primary" @click="testConnection">测试连接</el-button>
        <el-button style="margin-top: 12px" v-if="((active === 2) || (dataForm.actionType === '3' && active === 1)) && (type != 'view')" type="primary" @click="determine">保存</el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {submit, detail, getMessageList, testConnection} from "@/api/warning/warning-action-api";

import {getPage as getTemplatePage} from "@/api/message/template";
import {getPage as getChannelPage} from "@/api/message/channel";
import {
  aliyunConfigData,
  tencentConfigData,
  mailConfigData,
  systemMessageData
} from '../messageData/messageConfigData'
import { listSimpleUsers } from '@/api/system/user'
import {VueEditor} from "vue2-editor";

export default {
  name: "actionAdd",
  components: {
    VueEditor
  },
  data() {
    return {
      tagValueList:{},
      isClear:false,
      inputValue:'',
      inputVisible:false,
      // 用户列表
      users: [],
      type: 'add',
      configData:[],
      msgTemplate:{},
      msgChannel:{},
      templateDisabled:true,
      channelList:[],
      templateList:[],
      title: '动作新增',
      dialogFlag: false,
      messageShow: false,
      actionDict: [],
      mqttQosDict: [],
      retainDict: [],
      httpRequestDict: [],
      outputWayDict: [],
      active: 0,
      dataForm: {
        actionName: '',
        actionType: '',
        outputWay: '',
        message:{
          msgChannel:'',
          msgTemplate:'',
          users:''
        },
      },
      rules: {
        'message.msgTemplate':[
          {
            required: true,
            message: '请选择消息模板',
            trigger: 'blur'
          }
        ],
        actionName: [
          {
            required: true,
            message: "请输入动作名称",
            trigger: 'blur'
          },
        ],
        actionType: [
          {
            required: true,
            message: "请选择动作类型",
            trigger: 'blur change'
          }
        ]
      },
    }
  },
  created() {
    //获取通道列表渲染
    let param={
      pageNum:1,
      pageSize:999999
    }
    getChannelPage(param).then(res=>{
      this.channelList=res.data.records
    })

    // 获得用户列表
    listSimpleUsers().then(response => {
      this.users = response.data;
    })
  },
  mounted() {
    this.actionDict = this.$store.state.dict.dictDatas.action_type
  },
  methods: {
    handleClose(tag,prop) {
      this.dataForm.message[prop].splice(this.dataForm.message[prop].indexOf(tag), 1);
    },
    showInput(prop) {
      for (let i = 0; i < this.configData.length; i++) {
        if (this.configData[i].prop==prop){
          this.$set(this.configData[i],'isShow',!this.configData[i].isShow)
          //初始化值
          this.$set(this.tagValueList,prop,'')
        }
      }
      this.$nextTick(_ => {
        this.$refs[prop][0].$refs.input.focus();
      });
    },
    handleInputConfirm(prop) {
      if (!this.dataForm.message[prop] || this.dataForm.message[prop]==""){
        this.dataForm.message[prop]=[]
      }

      if (this.tagValueList[prop]) {
        this.dataForm.message[prop].push(this.tagValueList[prop]);
      }
      for (let i = 0; i < this.configData.length; i++) {
        if (this.configData[i].prop==prop){
          this.$set(this.configData[i],'isShow',false)
        }
      }
      this.tagValueList[prop] = '';
    },
    usersChange(val){
    },
    //从dataForm中获取配置参数 构建并设置 relatedParameter 到 dataForm
    getConfigData(channelType,relatedParameter){
      switch (channelType) {
        case 0:{
          return systemMessageData
        }
        default :
          return []
      }
    },
    selectTemplate(templateVal){
      let that =this
      this.templateList.filter(item=>{
        if (item.templateId==templateVal){
          that.msgTemplate=item
          return item
        }
      })
      this.$set(this.dataForm.message,'msgTemplate',templateVal)
      this.dataForm.message.templateId=templateVal
      //先判断渠道类型
      let pushWays = JSON.parse(this.msgTemplate.pushWays)
      this.dataForm.outputWay=pushWays.channelType
      let relatedParameter = JSON.parse(this.msgTemplate.relatedParameter)
      //设置通道id和模板id
      relatedParameter.msgChannel=this.msgChannel.appId
      relatedParameter.msgTemplate=this.msgTemplate.templateId
      relatedParameter.templateId=this.msgTemplate.templateId
      this.dataForm.relatedParameter=relatedParameter
      //获取对应配置参数
      this.configData = this.getConfigData(pushWays.channelType,relatedParameter)
      this.isClear=true
    },
   async initTemplateList(channelId){
      let param={
        pageNum:1,
        pageSize:999999
      }
      //暂时这样过滤  后面写接口
     await getTemplatePage(param).then(res=>{
        this.templateList = res.data.records.filter(item=>{
          if (item.appId==channelId){
            return item
          }
        })
        if (this.templateList.length>0){
          this.templateDisabled=false
        }else {
          this.templateDisabled=true
        }
      })
    },
    selectChannel(channelVal){
      let that = this
      this.$set(this.dataForm.message,'msgTemplate',null)
      let param={
        pageNum:1,
        pageSize:999999
      }
      //暂时这样过滤  后面写接口
      getTemplatePage(param).then(res=>{
        this.templateList = res.data.records.filter(item=>{
            if (item.appId==channelVal){
              return item
            }
        })
         this.channelList.filter(item=>{
          if (item.appId==channelVal){
            that.msgChannel=item
          }
        })
        if (this.templateList.length>0){
          this.templateDisabled=false

        }else {
          this.templateDisabled=true
        }
      })
    },
    previous() {
      this.active--;
    },
    next() {
      switch (this.active) {
        case 0:
          this.active1();
          break;
        case 1:
          this.active2();
          break;
        case 2:
          this.active3();
          break;
      }
    },
    active1() {
      // 判断动作名称和动作类型是否为空
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //在去下一步前对需要使用的状态进行初始化
          if(this.dataForm.actionType=='1'&&this.dataForm.message==null){
            this.dataForm.message= {
                msgChannel:'',
                msgTemplate:'',
                users:''
            }
          }
          this.isClear=false
          this.active++
        }
      })
    },
    active2(){
      this.$refs.ruleForm.validate((valid) => {
        if (valid){
          //隐藏tag输入框 显示新增按钮
            this.inputVisible=false;
            if (this.msgTemplate.pushWays&&this.msgTemplate.relatedParameter){
              let pushWays = JSON.parse(this.msgTemplate.pushWays)
              let relatedParameter = JSON.parse(this.msgTemplate.relatedParameter)
              this.configData = this.getConfigData(pushWays.channelType,relatedParameter)
              this.dataForm.relatedParameter.channelType=pushWays.channelType
              //获取 模板处的json  对当前json进行属性赋值 以保持模板变动这边跟着变动
              this.setConfigDataReverse(relatedParameter,this.isClear)
              //设置保存时的json
              this.setNotContainConfigData(relatedParameter)
              //将relatedParameter
            }
          this.active++
        }
      })
    },
    addPoint() {
      this.title = "动作新增";
      this.type = 'add'
      this.dialogFlag = true;
    },
    setConfigData(relatedParameter){
      if (this.configData.length>0){
        for (let i = 0; i < this.configData.length; i++) {
          relatedParameter[this.configData[i].prop]=this.dataForm.message[this.configData[i].prop]
        }
      }
    },
    setNotContainConfigData(relatedParameter){
      let configDataProp=[]
      for (let i = 0; i <this.configData.length; i++) {
        configDataProp.push(this.configData[i].prop)
      }
      if (relatedParameter){
        // 使用for...in遍历可枚举属性
        for (const prop in relatedParameter) {
          if(!configDataProp.includes(prop)){
            this.dataForm.relatedParameter[prop]=relatedParameter[prop]
          }
        }
      }
    },
    //新增回显
    setConfigDataReverse(relatedParameter,isClear){
      if (this.configData.length>0){
        for (let i = 0; i < this.configData.length; i++) {
          //回显不需要编辑  不设置响应式  只设置relatedParameter有值的属性  说明该属性从模板取出来  可以空掉users自定义属性
          if (isClear){
              if (!this.configData[i].disabled){
                this.$set(this.dataForm.message,this.configData[i].prop,"")
                //this.dataForm.message[this.configData[i].prop] = ""
              }else {
                this.$set(this.dataForm.message,this.configData[i].prop,relatedParameter[this.configData[i].prop])
                //this.dataForm.message[this.configData[i].prop] = relatedParameter[this.configData[i].prop]
              }
          }else {
            if (relatedParameter[this.configData[i].prop]){
              this.$set(this.dataForm.message,this.configData[i].prop,relatedParameter[this.configData[i].prop])
              //this.dataForm.message[this.configData[i].prop] = relatedParameter[this.configData[i].prop]
            }
          }
        }
      }
    },
    // 编辑回显
   async editPoint(id) {
     let that = this
     this.type = 'edit'
     this.title = "动作编辑";
     await detail(id).then (async res => {
        this.dataForm = res.data
        if (this.dataForm.actionType=='1'){
          this.dataForm.relatedParameter=JSON.parse(this.dataForm.relatedParameter)
          await this.initTemplateList(this.dataForm.message.msgChannel)
          this.templateList.filter(template=>{
            if (template.templateId==that.dataForm.message.msgTemplate){
              that.msgTemplate=template
            }
          })
          this.channelList.filter(item=>{
            if (item.appId==that.dataForm.message.msgChannel){
              that.msgChannel=item
            }
          })
        }
        this.templateDisabled=false
      })
     this.dialogFlag = true
     this.active = 0
    },
    // 查看回显
    async viewPoint(id) {
      let that = this
      this.type = 'view'
      this.title = "动作查看";
      await detail(id).then (async res => {
        this.dataForm = res.data
        if (this.dataForm.actionType=='1'){
          this.dataForm.relatedParameter=JSON.parse(this.dataForm.relatedParameter)
          await this.initTemplateList(this.dataForm.message.msgChannel)
          this.templateList.filter(template=>{
            if (template.templateId==that.dataForm.message.msgTemplate){
              that.msgTemplate=template
            }
          })
          this.channelList.filter(item=>{
            if (item.appId==that.dataForm.message.msgChannel){
              that.msgChannel=item
            }
          })
        }
        this.templateDisabled=false
      })
      this.dialogFlag = true
      this.active = 0
    },
    // 确认按钮
    determine() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          //如果是发送消息  对Parameter进行处理
          if (this.dataForm.actionType=="1"){
            this.setConfigData(this.dataForm.relatedParameter)
            this.dataForm.relatedParameter=JSON.stringify(this.dataForm.relatedParameter)
          }

          submit(this.dataForm).then(res => {
            if (res.code === 0) {
              this.$message.success("操作成功")
              this.cancel();
            } else {
              this.$message.warning(res.msg);
            }
          })
        }
      })
    },
    cancel() {
      this.active = 0
      this.messageShow = false
      this.dialogFlag = false;
      //初始化dataForm
      this.dataForm =  {
        actionName: '',
          actionType: '',
          outputWay: '',
          message:{
          msgChannel:'',
            msgTemplate:'',
            users:''
        },
      };
      this.$refs['ruleForm'].clearValidate();
      this.$emit('restOnLoad');
    },
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 140px;
  margin-left: 10px;
  vertical-align: bottom;
}
.product-form ::v-deep .el-form-item__label {
  color: #3f4448;
  font-weight: 400;
}

.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 12px 0;
  border-top: 1px solid rgb(204, 204, 204);
}

.center-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
}
</style>
